<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>WebSocket测试</title>
</head>
<body>
<input type="text" id="message">
<button id="submit">提交</button>

<script>
    
    let websocket = new WebSocket("ws://127.0.0.1:8080/test");

    websocket.onopen = function () {
        console.log("连接成功");
    }

    websocket.onmessage = function (e) {
        console.log("收到消息: " + e.data);
    }

    websocket.onerror = function () {
        console.log("连接异常");
    }

    websocket.onclose = function () {
        console.log("连接关闭");
    }
    
    let input = document.querySelector('#message');
    let button = document.querySelector('#submit');
    
    button.onclick = function () {
        console.log("发送消息: " + input.value);
        // 建议添加连接状态判断，避免在未连接时发送消息
        if (websocket.readyState === WebSocket.OPEN) {
            websocket.send(input.value);
        } else {
            console.log("连接未建立，无法发送消息");
        }
    } 
</script>
</body>
</html>
